package cn.animal.common.exception;

import cn.animal.common.entity.po.Result;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> ex(MethodArgumentNotValidException ex) {
        // 获取第一个错误
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .findFirst()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .orElse("请求参数有误");
        return Result.error(errorMessage);
    }

    // 捕获所有异常
    @ExceptionHandler(Exception.class)
    public Result<Void> ex(Exception ex) {
        return Result.error(ex.getMessage());
    }

}
